/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.remove.impl;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.rpc.CompanyRpcService;
import com.je.rbac.service.remove.MoveService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

public abstract class AbstractMoveService implements MoveService {
    @Autowired
    public MetaService metaService;
    @Autowired
    public CommonService commonService;
    @Autowired
    private CompanyRpcService companyRpcService;

    /**
     * 在上面
     */
    public static final String ABOVE = "above";
    /**
     * 在下面
     */
    public static final String BELOW = "below";
    /**
     * 在里面
     */
    public static final String INSIDE = "inside";

    public static final String COMPANY = "company";

    public static final String DEPT = "department";

    /**
     * 确认平级
     *
     * @param soureceBean
     * @param targetBean
     * @return
     */
    public Boolean sameLevel(DynaBean soureceBean, DynaBean targetBean) {
        String soureceParentId = soureceBean.getStr("SY_PARENT");
        String targetParentId = targetBean.getStr("SY_PARENT");
        if (soureceParentId.equals(targetParentId)) {
            return true;
        }
        return false;
    }


    /***
     * 修改下级树形信息
     * @param dynaBean
     * @param oldBean
     */
    public void getUpdateChildTreeOrderIndexSql(DynaBean dynaBean, DynaBean oldBean) {
         dynaBean = metaService.selectOne("JE_RBAC_VCOMPANYDEPT",ConditionsWrapper.builder().eq("ID",dynaBean.getStr("ID")));
        //若当前节点是部门，并且部门的上级发生了改变，则修改部门下人员，账号相关公司，集团信息
        if("department".equals(oldBean.getStr("TYPE")) && !oldBean.getStr("SY_PARENT").equals(dynaBean.getStr("SY_PARENT"))){
            //递归处理部门下人员 公司，集团信息
            List<DynaBean> deptUserBeanList = metaService.select("JE_RBAC_DEPTUSER",ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID",oldBean.getStr("ID")));
            if(deptUserBeanList !=null && deptUserBeanList.size()>0){
                updateDeptUserCompanyInfo(oldBean.getStr("ID"));
            }
        }

        //递归修改子级树形信息
        List<DynaBean> childDynaBeanList =  findNextChildren(oldBean);
        updateDynaBeanTree(oldBean,childDynaBeanList);
    }

    /***
     * 添加bean KEY_TABLE_CODE，KEY_PK_CODE
     * @param dynaBean
     */
    public void updateDynaBeanTableInfo(DynaBean dynaBean){
        if(dynaBean.getStr("TYPE").equals("company")){
            dynaBean.set(BeanService.KEY_TABLE_CODE,"JE_RBAC_COMPANY");
            dynaBean.set(BeanService.KEY_PK_CODE,"JE_RBAC_COMPANY_ID");
            dynaBean.set("JE_RBAC_COMPANY_ID",dynaBean.getStr("ID"));
        }else if(dynaBean.getStr("TYPE").equals("department")){
            dynaBean.set(BeanService.KEY_TABLE_CODE,"JE_RBAC_DEPARTMENT");
            dynaBean.set(BeanService.KEY_PK_CODE,"JE_RBAC_DEPARTMENT_ID");
            dynaBean.set("JE_RBAC_DEPARTMENT_ID",dynaBean.getStr("ID"));
        }
    }

    /***
     * 获取子级bean数据
     * @param dynaBean
     * @return
     */
    public List<DynaBean> findNextChildren(DynaBean dynaBean) {
        return metaService.select("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().eq("SY_PARENT", dynaBean.getPkValue())
                .or(false).eq(false, "ID", dynaBean.getPkValue()).orderByAsc("SY_ORDERINDEX"));
    }

    /***
     * 目标节点前面，后面
     * 构建原节点（公司，部门） 公司，集团信息
     * @param resourceBean
     * @param targetBean
     */
    public void buildCompanyInfo(DynaBean resourceBean, DynaBean targetBean){
        DynaBean targetParent = new DynaBean();
        if(!"ROOT".equals(targetBean.getStr("SY_PARENT"))){
             targetParent = metaService.selectOne("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().eq("ID", targetBean.getStr("SY_PARENT")));
        }

        //resourceBean 如果是公司 修改公司，集团信息；
        //resourceBean 如果是 部门 修改公司，集团信息，上级部门名称（若上级是公司则名称为ROOT,），父级节点类型
        if(resourceBean.getStr("TYPE").equals("company") ){
            resourceBean.setStr("SY_GROUP_COMPANY_ID",targetBean.getStr("SY_GROUP_COMPANY_ID"));
            resourceBean.setStr("SY_GROUP_COMPANY_NAME",targetBean.getStr("SY_GROUP_COMPANY_NAME"));
        }else if(resourceBean.getStr("TYPE").equals("department")){
            if(targetBean.getStr("TYPE").equals("company")){
                resourceBean.setStr("PARENT_NODETYPE",targetParent.getStr("TYPE"));
                resourceBean.setStr("SY_COMPANY_ID",targetBean.getStr("SY_GROUP_COMPANY_ID"));
                resourceBean.setStr("SY_COMPANY_NAME",targetBean.getStr("SY_GROUP_COMPANY_NAME"));
                //查询当前目标父级的上级
                DynaBean groupCompanyBean = companyRpcService.findParent(targetBean.getStr("SY_GROUP_COMPANY_ID"));
                if(groupCompanyBean !=null){
                    resourceBean.setStr("SY_GROUP_COMPANY_ID",groupCompanyBean.getStr("JE_RBAC_COMPANY_ID").equals("ROOT")? "" : groupCompanyBean.getStr("JE_RBAC_COMPANY_ID"));
                    resourceBean.setStr("SY_GROUP_COMPANY_NAME",(groupCompanyBean.getStr("COMPANY_NAME") == null || Strings.isNullOrEmpty(groupCompanyBean.getStr("COMPANY_NAME")))? "" : groupCompanyBean.getStr("COMPANY_NAME"));
                }
            }
            if(targetBean.getStr("TYPE").equals("department")){
                resourceBean.setStr("SUPERIOR_DEPARTMENT",(targetParent.getStr("TYPE").equals("company"))? "" : targetParent.getStr("NAME") );
                resourceBean.setStr("PARENT_NODETYPE",targetParent.getStr("TYPE"));
                resourceBean.setStr("SY_COMPANY_ID",targetBean.getStr("SY_COMPANY_ID"));
                resourceBean.setStr("SY_COMPANY_NAME",targetBean.getStr("SY_COMPANY_NAME"));
                resourceBean.setStr("SY_GROUP_COMPANY_ID",targetBean.getStr("SY_GROUP_COMPANY_ID"));
                resourceBean.setStr("SY_GROUP_COMPANY_NAME",targetBean.getStr("SY_GROUP_COMPANY_NAME"));
            }
        }
    }

    /***
     * 目标节点里面
     * 构建原节点（公司，部门） 公司，集团信息
     * @param resourceBean
     * @param parentBean
     */
    public void buildTargetInsideCompanyInfo(DynaBean resourceBean, DynaBean parentBean){
//        DynaBean targetParent = metaService.selectOne("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().eq("SY_PARENT", targetBean.getStr("SY_PARENT")));

        //resourceBean 如果是公司 修改公司，集团信息；
        //resourceBean 如果是 部门 修改公司，集团信息，上级部门名称（若上级是公司则名称为ROOT,），父级节点类型
        if(resourceBean.getStr("TYPE").equals("company") ){
            resourceBean.setStr("SY_GROUP_COMPANY_ID",parentBean.getStr("ID"));
            resourceBean.setStr("SY_GROUP_COMPANY_NAME",parentBean.getStr("NAME"));
        }else if(resourceBean.getStr("TYPE").equals("department")){
            if(parentBean.getStr("TYPE").equals("company")){
                resourceBean.setStr("PARENT_NODETYPE",parentBean.getStr("TYPE"));
                resourceBean.setStr("SY_COMPANY_ID",parentBean.getStr("ID"));
                resourceBean.setStr("SY_COMPANY_NAME",parentBean.getStr("NAME"));
                //查询当前目标父级的上级
                DynaBean groupCompanyBean = companyRpcService.findParent(parentBean.getStr("ID"));
                if(groupCompanyBean !=null){
                    resourceBean.setStr("SY_GROUP_COMPANY_ID",groupCompanyBean.getStr("JE_RBAC_COMPANY_ID").equals("ROOT") ? "" : groupCompanyBean.getStr("JE_RBAC_COMPANY_ID") );
                    resourceBean.setStr("SY_GROUP_COMPANY_NAME",(groupCompanyBean.getStr("COMPANY_NAME") == null || Strings.isNullOrEmpty(groupCompanyBean.getStr("COMPANY_NAME")))? "" : groupCompanyBean.getStr("COMPANY_NAME"));
                }
            }
            if(parentBean.getStr("TYPE").equals("department")){
                resourceBean.setStr("SUPERIOR_DEPARTMENT",parentBean.getStr("NAME") );
                resourceBean.setStr("PARENT_NODETYPE",parentBean.getStr("TYPE"));
                resourceBean.setStr("SY_COMPANY_ID",parentBean.getStr("SY_COMPANY_ID"));
                resourceBean.setStr("SY_COMPANY_NAME",parentBean.getStr("SY_COMPANY_NAME"));
                resourceBean.setStr("SY_GROUP_COMPANY_ID",parentBean.getStr("SY_GROUP_COMPANY_ID"));
                resourceBean.setStr("SY_GROUP_COMPANY_NAME",parentBean.getStr("SY_GROUP_COMPANY_NAME"));
            }
        }
    }


    /***
     * 递归修改树形属性
     */
    private void updateDynaBeanTree(DynaBean parentBean,List<DynaBean> childBeanList) {
        if (childBeanList == null || childBeanList.isEmpty()) {
            return;
        }
        //查询已被修改过的父级树形属性
        DynaBean parentUpdateBean = metaService.selectOne(parentBean.getTableCode(),ConditionsWrapper.builder().eq(parentBean.getPkCode(), parentBean.getStr("ID")));
        DynaBean parentBeanData = metaService.selectOne("JE_RBAC_VCOMPANYDEPT",ConditionsWrapper.builder().eq("ID",parentBean.getStr("ID")));
        for (DynaBean eachBean : childBeanList) {
            updateDynaBeanTableInfo(eachBean);
            if(parentBean.getStr("ID").equals(eachBean.getStr("SY_PARENT"))){
                int currentChildCount = 0;
                List<Map<String,Object>> currentChildList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_VCOMPANYDEPT WHERE SY_PARENT = {0}",parentBean.getStr("ID"));
                if(currentChildList.size()>0){
                    currentChildCount = (int) currentChildList.get(0).get("MAX_COUNT");
                }
                eachBean.setStr("SY_PARENT",parentUpdateBean.getStr(parentUpdateBean.getPkCode()));
                eachBean.setStr("SY_PARENTPATH",parentUpdateBean.getStr("SY_PATH"));
                eachBean.setStr("SY_NODETYPE",(findNextChildren(eachBean)!=null && findNextChildren(eachBean).size()>0)? "GENERAL" : "LEAF");
                eachBean.setStr("SY_ORDERINDEX",(currentChildCount+1)+"");
                eachBean.setStr("SY_TREEORDERINDEX",parentUpdateBean.getStr("SY_TREEORDERINDEX") + String.format("%06d", currentChildCount+1));
                eachBean.setStr("SY_LAYER",parentUpdateBean.getStr("SY_LAYER")+ 1);
                eachBean.setStr("SY_PATH",parentUpdateBean.getStr("SY_PATH") + "/" + eachBean.getStr(eachBean.getPkCode()));

                //resourceBean 构建公司，集团信息
                buildTargetInsideCompanyInfo(eachBean,parentBeanData);

                if(eachBean.getTableCode().equals("JE_RBAC_DEPARTMENT")){
                    metaService.update(eachBean);
                    //修改部门下人员，账号相关公司 集团信息
                    updateDeptUserCompanyInfo(eachBean.getStr("JE_RBAC_DEPARTMENT_ID"));
                }else if(eachBean.getTableCode().equals("JE_RBAC_COMPANY")){
                    metaService.update(eachBean);
                }
            }
        }

        for (DynaBean eachBean : childBeanList) {
            updateDynaBeanTableInfo(eachBean);
            updateDynaBeanTree(eachBean, findNextChildren(eachBean));
        }
    }

    public void treeIndexAddOne(DynaBean dynaBean) {
        String treeIndex = dynaBean.getStr("SY_TREEORDERINDEX");
        int intTreeIndex = Integer.parseInt(treeIndex.substring(treeIndex.length() - 6)) + 1;
        treeIndex = treeIndex.substring(0, treeIndex.length() - 6) + String.format("%06d", intTreeIndex);
        dynaBean.set("SY_ORDERINDEX", intTreeIndex);
        dynaBean.set("SY_TREEORDERINDEX", treeIndex);

        String syParent = dynaBean.getStr("SY_PARENT");
        if(dynaBean.getStr("PARENT_NODETYPE").equals("company")){
            syParent = "ROOT";
        }
        dynaBean.setStr("SY_PARENT", syParent);
        dynaBean.setStr("SY_NODETYPE",(findNextChildren(dynaBean)!=null && findNextChildren(dynaBean).size()>0)? "GENERAL" : "LEAF");
        metaService.update(dynaBean);
    }

    /***
     * 修改部门下级 人员，账号（公司，集团数据）
     * @param deptId
     */
    public void updateDeptUserCompanyInfo(String deptId) {
        //若移动到其他公司下，则需修改
        // 部门所属公司，集团公司信息；
        // （子级部门，人员（所属公司，集团公司信息））；
        //JE_RBAC_ACCOUNTDEPT 账号部门关联表 所属公司，集团公司信息
        DynaBean deptBean = metaService.selectOne("JE_RBAC_DEPARTMENT",ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID",deptId));
        List<DynaBean> deptUserBeanList = metaService.select("JE_RBAC_DEPTUSER",ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID",deptId));

        if(deptBean !=null && deptUserBeanList !=null && deptUserBeanList.size()>0){
            DynaBean companyBean = metaService.selectOne("JE_RBAC_COMPANY",ConditionsWrapper.builder().eq("JE_RBAC_COMPANY_ID",deptBean.getStr("SY_COMPANY_ID")));
            //修改部门人员 所属公司，集团公司信息
            metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET SY_GROUP_COMPANY_ID={0},SY_GROUP_COMPANY_NAME={1},SY_COMPANY_ID={2},SY_COMPANY_NAME={3},SY_COMPANY_CODE={4}  WHERE JE_RBAC_DEPARTMENT_ID={5}",
                    deptBean.getStr("SY_GROUP_COMPANY_ID"),deptBean.getStr("SY_GROUP_COMPANY_NAME"),companyBean.getStr("JE_RBAC_COMPANY_ID"),companyBean.getStr("COMPANY_NAME"),companyBean.getStr("COMPANY_CODE"),deptBean.getStr("JE_RBAC_DEPARTMENT_ID"));

            //修改用户相关账号JE_RBAC_ACCOUNTDEPT 账号部门关联表 所属公司，集团公司信息
            metaService.executeSql("UPDATE JE_RBAC_ACCOUNTDEPT SET SY_GROUP_COMPANY_ID={0},SY_GROUP_COMPANY_NAME={1},SY_COMPANY_ID={2},SY_COMPANY_NAME={3} WHERE  ACCOUNTDEPT_DEPT_ID={4}",
                    deptBean.getStr("SY_GROUP_COMPANY_ID"),deptBean.getStr("SY_GROUP_COMPANY_NAME"),companyBean.getStr("JE_RBAC_COMPANY_ID"),companyBean.getStr("COMPANY_NAME"),deptBean.getStr("JE_RBAC_DEPARTMENT_ID"));
        }
    }

}
